Repository navigation
Per-bin work of integer planes in NumPy int64 (speed plan D6), bitwise v0.7.0 - #104
Conversation
The bin starts, the sums of per-value counts into bins, the integer bin limits, the representatives, max_representative_error and the bin of each order statistic of the range check were Python loops over every bin (a 65,537-item list per plane and call). New module integer_bins computes the same integers with NumPy int64, and keeps v0.7.0's exact Python integers where int64 could not be exact: bin_count * width >= 2**62, pixels from 2**51 on, per-value totals from 2**52 on, and histograms built with NumPy integer limits. Every output is bitwise v0.7.0's; no new dependency. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc
tests/histogram_parity_cases.py ports the preprocessing study's differential check (PR #318, diffcheck.py), made smaller: 4,236 cases over the ten pixel types, NaN/inf, subnormals, constant/empty/extreme planes, bin-edge float grids, several bin counts, min-max and robust, whole and in 3 blocks, and 64-bit ranges on both sides of every int64 condition. tests/data/histogram_v070_parity.json is its table recorded on v0.7.0 (c6a9f9d). test_histogram_parity.py checks every plane against it, the kept Python path with the int64 path switched off, a negative control, and each int64 formula and condition against the Python integers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc
The preprocessing study's data and scripts (PR #318), preprocessing v0.6.1, 5 interleaved repeats of v0.7.0 and this change at workers 1/2/4/auto on a shared 4-CPU machine; median (min-max) wall times in the CHANGELOG. All 40 runs wrote identical bytes in every output file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc
3164dc6 to
a70b0df
Compare
A caller-built PlaneHistogram may carry a NumPy integer bin count. Then bin_count * width in integer_bin_starts_int64 is a NumPy product that wraps silently: a uint64 histogram over 0 .. 2**50 with np.int64(65_536) bins got negative bin limits and representatives, where v0.7.0 raised OverflowError; narrower ranges returned Python ints where v0.7.0 gave np.int64 limits and an np.float64 bound. integer_bin_offsets now takes the int64 path only when the bin count is a Python int as well, so these histograms keep v0.7.0's values, types and refusals. Computed histograms are unaffected (validate_bin_count returns int). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc
guijacquemet
left a comment
There was a problem hiding this comment.
Independent review: PASS after one fix (5373049)
Defect found and fixed: a NumPy bin count on a caller-built histogram
integer_bin_offsets checked that the limits were Python ints, but not the bin count. PlaneHistogram does not convert bin_count, so a caller can pass np.int64(65_536). Then bin_count * max(width, 1) in integer_bin_starts_int64 is a NumPy product that wraps silently, and the 2**62 guard passes.
- Example: a uint64 histogram over
0 .. 2**50withnp.int64(65_536)bins. Ona70b0dfit got negative bin limits (last bin(-17179869183, 0)) and negative representatives, with no error. v0.7.0 raisedOverflowErrorhere. - Narrower ranges: with a NumPy bin count it returned Python
intlimits and afloatbound, where v0.7.0 gavenp.int64limits andnp.float64.
Fix: the int64 path now also needs type(bin_count) is int, so these histograms keep v0.7.0's values, types and refusals. Computed histograms are not affected, because validate_bin_count returns int.
- Regression test:
test_bin_offsets_keep_python_integers_for_a_numpy_bin_count. It fails ona70b0dfand passes with the fix. - The CHANGELOG line is updated.
Exactness of each int64 path (checked against the v0.7.0 formulas)
- Starts: with
n*W < 2**62,|i*W| < 2**62and NumPy's floor division is Python's, so the starts are the same integers. Thewidth <= nbranch is the same. - Per-value sums: the guard is the float64 total
< 2**52. Below2**53, every partial sum of non-negative counts is exact in float64, so the guard itself is exact, and v0.7.0'sbincount+rintequals the int64 cumsum differences. The threshold could be2**53;2**52is conservative. - Representatives: the invariant
pixel_min <= binning_min <= binning_max <= pixel_maxandbeyond_float_exactkeep|first+lo + last+lo| < 2**52. So the int64 sum is exact in float64 and/2is exact, which is the same as Python's correctly roundedint / 2. max_representative_error: the widest bin is the same integer.integer_bin_index: the count ofi < nwithceil(i*W/n) <= oismin(floor(o*n/W), n-1) + 1. It uses Python ints only (_key_valuegives.item(), and the limits are Python ints), so floor semantics and negatives match:o < 0gives -1, asbisectdoes.- Types at public boundaries:
integer_bin_limits()uses.tolist(), so it returns Python ints; the bound is a float andRangeCheckfields are ints. These match v0.7.0.
Parity table
- I re-recorded the whole table on a
c6a9f9dworktree. It is byte-identical totests/data/histogram_v070_parity.json. - Parity tests: 396 passed on
a70b0df, 397 with the fix. - Branch coverage of the table-only test over
integer_bins: every int64/Python choice that real computations can reach is hit on both sides.- The table never reaches the
offset < 0andwidth <= nbranches ofinteger_bin_index: no non-exact histogram has a range check withwidth <= n. The exhaustivebisectunit test covers them. - The float64 fallback of
counts_from_per_valuecannot be reached from a plane in memory; a unit test covers it.
- The table never reaches the
- The negative control works: one bin off, or one ulp off, changes the digest.
Identity, reproduced
| Check | Result |
|---|---|
tools/check.py (fix head) |
2,630 passed, 90 skipped (scikit-image extra; the CI histology job ran them), rules OK |
Preprocessing v0.6.1 37c583e, this branch --no-deps: test_run_workers_bytes.py (v05, v09) |
4 passed |
| Full preprocessing v0.6.1 suite (zarr, notebook and dev extras) | 6,021 passed, 4 skipped (platform skips: case-sensitive file system, root ignoring file modes) |
| Benchmark data (scale 1, fixed clock): v0.7.0 vs branch, workers 1 and 4, 16 runs in all | all 6 files' SHA-256 identical to v0.7.0 serial |
Signed zero
Confirmed pre-existing on v0.7.0. compute_plane_histogram gives pixel_min = -0.0 for [0.0, -0.0, 1.0] and +0.0 for [-0.0, 0.0, 1.0]: it follows ndarray.min, which depends on element order and layout.
- The float path is untouched by this diff.
+ 0.0is applied only in_float_plane. It does not consume the random generator, and integer planes are generated separately, so it hides nothing about the int path.- Not fixed here. I agree it is an owner decision.
Speed (shared 4-CPU machine, load about 1.0–1.3, fresh process per run, 3 repeats, interleaved)
| workers | v0.7.0 | branch | speed-up |
|---|---|---|---|
| 1 | 6.48 s (6.28–6.54) | 4.91 s (4.88–4.94) | 1.32× |
| 4 | 5.47 s (5.47–5.97) | 4.06 s (3.84–4.43) | 1.35× |
Median CPU time: 6.6 → 5.0 s serial and 7.1 → 5.8 s at 4 workers. The ranges do not overlap. The serial gain is smaller than the stated 1.46×, mostly because v0.7.0 ran faster here on a less loaded machine; it is the same order.
CI is 10/10 green on 5373049. Merging.
Generated by Claude Code
Step D6 of the preprocessing speed plan. Owner decision (16 Nov): no Numba; do the exact NumPy change here. Evidence: preprocessing draft PR #318,
experiments/histogram_numba_study/(itsnumba_patch.pynumpy-binsmode is the sketch this follows).Do not merge yet: an independent review comes first. No tag.
What changes (commit 1,
f78cd0b)Until now, every integer plane ran Python loops over every bin, on preprocessing's calling thread:
_integer_bin_startsbuilt a 65,537-item list per call. It ran once for the counts, again for the cached bin limits, and 4× for the range check's_bin_index+bisect.representativesandmax_representative_errorwere list comprehensions over the bins._counts_from_per_valuebuilt the bin index of every value from that list.New pure module
integer_bins(moved out ofhistogram.py, which shrinks; layer and AGENTS map added). It keeps the same formulas:ceil(i*W/n)/min(i, W)arangearithmetic (NumPy floor division = Python's)bin_count * width >= 2**62(64-bit planes with a wide range), soi*widthcan never overflow>= 2**52: v0.7.0's float64bincount+rintis kept, so even its rounding beyond2**53is unchanged (unreachable for one plane in memory)_integer_bin_limits)ints (a caller's NumPy integers): v0.7.0's lists, so its result types (np.int64,np.float64) stay toorepresentatives((first+lo)+(last+lo)).astype(float64)/2: exact below2**532**51(beyond_float_exact), or no int64 limits; theFractionbound (#28) is unchangedmax_representative_errorint((last-first).max()) + 1offset*n // width, oroffsetifwidth <= nUnchanged: float binning and bin positions, tail moments (exact rationals), 32/64-bit pixel binning, and the radix selection. There is no new dependency, and no API, file-format or message change. CHANGELOG
## Unreleasedis updated.Identity
Permanent differential test (commit 2,
74d72a0).tests/histogram_parity_cases.pyports the study'sdiffcheck.py, made smaller: 4,236 cases.nextafterneighbours);n*Wjust below and at2**62, below2**51but too wide for int64 at 65,536 bins, at2**51, and the full uint64 top half.PlaneHistogramfield (arrays and floats as raw bytes),representatives,max_representative_error,integer_bin_limits()values and types,is_exact, and theRangeCheck, from bothcompute_block_histogramandhistogram_with_range_check.tests/data/histogram_v070_parity.jsonis the table recorded on v0.7.0 (c6a9f9d) (one SHA-256 per plane, 23 KB).tests/test_histogram_parity.pychecks:INT64_STARTS_LIMIT = 0): the kept Python path gives the same bits;bisectcheck of the bin index;2**62,2**52totals with[2**53, 1], NumPy-integer limits).-0.0and+0.0(+ 0.0is added to every float plane), and an all--0.0plane covers negative zero.pixel_min/pixel_maxbits than Linux for the six planes that mixed them, while Linux passed.finite.min()/max()). The cause is inferred: NumPy may return either zero depending on the platform. v0.7.0 itself was not run on those runners.plane_histograms.csvsay-0.0on one OS and0.0on another for the same pixels.Further identity checks on this machine:
diffcheck.pycase set, run in separate processes on v0.7.0 and on this branch and compared field by field: 0 of 5,580 cases differ.tools/dump_outputs.py, base vs. change: default032b395b…(1,788 lines) and--corpus0111f8bd…(4,764 lines), the same on both.tools/check.py: 2,629 passed, 90 skipped. The skips are the scikit-image extra, the same as on base, which CI'shistologyjob runs.test_fit_goldens.py, the stain and region parity tables) pass.Preprocessing v0.6.1 (
37c583e) with this branch installed--no-deps:tests/test_run_workers_bytes.py(Spec fixtures v05, v09, workers 1/2/4/auto) andtests/test_histogram_goldens.py(12): 15 passed.--basetempand the inputs' mtimes pinned, since the manifest records them and the test writes new inputs each session. Result: 10 runs, 60 files, 0 differ (CSV, design, manifest, reports).test_notebook_design_confirm_speed.py::test_the_click_saves_once…, a wall-clock assertion on a machine with load average about 3.Speed (commit 3,
a70b0df)Setup:
benchmark_run_workers.write_datasetat scale 1, 14 images, 76 planes, 303 MiB, memory limit 64 MiB.runonce.py: a fresh process per run, fixed clock.bench.py, with v0.7.0 and this change selected byPYTHONPATH(the module path was checked for each variant).Wall time of
run_experiment, median (min–max):This matches the study's
numpy-bins(1.48× serial, 1.31× at 4 workers). At every worker count, the slowest run of this change is faster than the fastest run of v0.7.0 (the min–max ranges do not overlap).The normalization suite also gets faster: 51 s → 20 s on the old tests; 45 s with the new parity tests.
Release (not done here)
This needs normalization v0.7.1 (patch: version bump + CHANGELOG heading, tag by the owner), then re-pins of the bricks that pin
@v0.7.0:pyproject.toml.versions.pywritesmorphobricks_normalization.__version__intorun_manifest.json, so manifests will say 0.7.1 by design. Checktest_manifest.py,test_notebook_setup.pyand the histogram goldens for a hard-coded 0.7.0.setup.py(+tests/test_dependency_pins.py).pyproject.toml(+tests/test_dependency_pins.py). Its normalization requirement must equal the one in the preprocessing release it pins, so re-pin it after preprocessing.Follow-up outside D6 (not a speed item)
_wide_histogramtakespixel_min/pixel_maxof float planes from NumPy'smin/max. For a plane holding both-0.0and+0.0, the sign of the result differs between platforms (Linux vs. the Windows and macOS runners), so its text and bits inplane_histograms.csvcan differ.-0.0whenever present) is a behaviour change for the owner.Not done here: candidates for step D8 (own PRs)
csv_io.table_headerrebuilds the 131,110 column names for every staged file. It could be cached per (channel IDs, bin count).csv_io._rowformats the counts withmap(str, counts.tolist());csv.writercell writing is >50% of GIL time after this change. A faster exact formatter needs its own byte-identity study.csv_io._histogramparses counts from text withnp.array(list_of_str, int64).summaries._saturated_fractionbuilds the wholeinteger_bin_limits()list to read one bin. It could read the cached int64 limits.integer_bin_limits()still returns a list of tuples by design (public API). Internal callers could use the arrays instead.wide_integer_error(64-bit beyond2**51) loops inFractionover every bin. This is exact by design; vectorising it is not easy and is rarely hit.🤖 Generated with Claude Code
https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc